<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Book extends Model {
	
	protected $guarded = array('id');
	
	public function sections() {
		return $this->hasMany('App\Models\Section');
	}
	
	public function category() {
		return $this->belongsTo('App\Models\Category');
	}
	
	public function comments() {
		return $this->hasMany('App\Models\Comment')->orderBy('id', 'desc');
	}
	
	public function thumbnailUrl() {
		$thumbnail = $this->thumbnail;
		if (!starts_with($this->thumbnail, 'http')) {
			$thumbnail = asset('/uploads/covers/'. $this->thumbnail);
		}
		return $thumbnail;
	}
	
	public function getFirstSection() {
		$section = Section::where('book_id', $this->id)
				->orderBy('order')
				->first();
		return $section ? $section : null;
	}
	
	public function getLastSection() {
		$section = Section::where('book_id', $this->id)
				->orderBy('order', 'desc')
				->first();
		return $section ? $section : null;
	}
	
	const BIQUGE = 'biquge';
	const SHUQIBA = 'shuqiba';
	const QUANSHUWU = 'quanshuwu';
	
	public static $source = [
		self::BIQUGE => '笔趣阁',
		self::SHUQIBA => '书旗吧',
		self::QUANSHUWU => '全本书吧',
	];
	
	public function source_ex() {
		return self::$source[$this->source];
	}
	
	public static $rules = [
		'name' => 'required',
		'author' => 'required',
		'category_id' => 'required'
	];
	
	public static $msgs = [
		'name.required' => '小说名称不能为空',
		'author.required' => '小说作者不能为空',
		'category_id.required' => '小说分类不能为空'
	];
}
